import 'dart:io';

import 'package:FineArt/components/rounded_button.dart';
import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/user_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/splash/role_choose.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:image_picker/image_picker.dart';
import 'package:package_info/package_info.dart';

class EditMyPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _EditMyPageState();
  }
}

class _EditMyPageState extends State<EditMyPage> {
  String versionName = "";
  String userName;
  Size _size;

  UserInfo userInfo;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
      setState(() {
        versionName = packageInfo.version + "." + packageInfo.buildNumber;
      });
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getMyInfo();
  }

  @override
  Widget build(BuildContext context) {
    _size = MediaQuery.of(context).size;
    // SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]);
    // TODO: implement build
    return WillPopScope(
      onWillPop: () {
        Navigator.of(context).pop(false);
      },
      child: Scaffold(
          backgroundColor: bg_button_gray,
          appBar: AppBar(
            toolbarHeight: 0,
            brightness: Brightness.dark,
            // title: Text("mypage"),
            // automaticallyImplyLeading: true,
            // centerTitle: true,
            elevation: 0,
            backgroundColor: Colors.red,
          ),
          body: Stack(children: [
            Positioned(
              child: buildHeader(),
              top: 0,
            ),
            Positioned(child: _buildContainer(), top: getPortraitSHeight(150)),
          ])),
    );
  }

  Widget _buildContainer() {
    return Container(
      color: Color(0xfff2f2f2),
      width: _size.width,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: _buildListChild(),
        ),
      ),
    );
  }

  List<Widget> _buildListChild() {
    return [
      //头像
      // buildHeader(),
      SizedBox(
        height: getPortraitSHeight(7),
      ),
      buildCommonItem("头像", "", () {
        _showBottomMenu(context);
      }, true),
      buildCommonItem("姓名", userInfo.nickname, () {}, false),
      buildCommonItem("性别", userInfo.gender == 0 ? "男" : "女", () {}, false),
      buildCommonItem("身份", userInfo.role, () {}, false),
      buildCommonItem("院校", userInfo.org, () {}, true),
    ];
  }

  ///构建头像
  Widget buildAvatar() {
    return Center(
      child: Container(
        margin: EdgeInsets.only(top: 10, bottom: 10),
        width: 100,
        height: 100,
      ),
    );
  }

  Widget buildHeader() {
    return Container(
      padding: EdgeInsets.only(top: 10),
      color: Colors.red,
      width: _size.width,
      height: getPortraitSHeight(154),
      child: Column(
        children: [
          Row(
            children: [
              SizedBox(
                width: getPortraitSWidth(12),
              ),
              InkWell(
                child: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                ),
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),
              SizedBox(
                width: getPortraitSWidth(135),
              ),
              Text(
                "我的",
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
          Row(
            children: [
              Padding(
                padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                child: _image != null
                    ? Image.file(
                        File(_image.path.toString()),
                        width: 80,
                        height: 80,
                        fit: BoxFit.cover,
                      )
                    : Image.asset("assets/images/bg_header.png", width: 80),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                      width: _size.width - 120,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            userInfo == null
                                ? ""
                                : userInfo.nickname ?? userInfo.nickname,
                            style: TextStyle(color: Colors.white, fontSize: 16),
                          ),
                        ],
                      )),
                  SizedBox(
                    height: 5,
                  ),
                  Row(
                    children: [
                      buildClasses(),
                      SizedBox(
                        width: 10,
                      ),
                      Container(
                        decoration: BoxDecoration(
                            color: Colors.green,
                            borderRadius: BorderRadius.all(Radius.circular(5))),
                        padding:
                            EdgeInsets.symmetric(vertical: 2, horizontal: 6),
                        child: Text(
                          "已激活",
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ],
                  )
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  Row buildClasses() {
    if (userInfo == null) return Row();
    if (userInfo.classes.isEmpty) return Row();

    List<Container> classes = [];
    for (ClassInfo info in userInfo.classes) {
      Container c = Container(
        decoration: BoxDecoration(
            color: Colors.blue,
            borderRadius: BorderRadius.all(Radius.circular(5))),
        padding: EdgeInsets.symmetric(vertical: 2, horizontal: 6),
        margin: EdgeInsets.only(right: 3),
        child: Text(
          info.classname,
          style: TextStyle(color: Colors.white),
        ),
      );

      classes.add(c);
    }

    if (classes.length > 2) classes = classes.sublist(0, 2);

    return Row(children: classes);
  }

  Widget buildRoundText(
      String text, Function press, Color color, Color bgColor) {
    return InkWell(
      onTap: press,
      child: Container(
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: BorderRadius.all(Radius.circular(25))),
        padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
        child: Text(
          text,
          style: TextStyle(color: color, fontSize: 15),
        ),
      ),
    );
  }

  //构建通用item
  Widget buildCommonItem(
      String name, String itemContent, Function clickListener, bool showRight) {
    return InkWell(
      child: Container(
        color: Colors.white,
        height: getPortraitSHeight(50),
        margin: EdgeInsets.symmetric(horizontal: getPortraitSWidth(12)),
        padding: EdgeInsets.only(left: getPortraitSWidth(16), right: 15.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            getBadgeText(name),
            Expanded(
              child: Text(""),
            ),
            Padding(
              padding: EdgeInsets.only(right: 10),
              child: getBadgeText(itemContent),
            ),
            getRightArrow(showRight),
          ],
        ),
      ),
      onTap: clickListener,
    );
  }

  Widget getRightArrow(bool showRight) {
    if (showRight) {
      return Image.asset(
        "assets/images/icon_right_arrow.png",
        width: getPortraitSWidth(8.5),
        height: getPortraitSHeight(14.5),
      );
    } else {
      return SizedBox(
        width: getPortraitSWidth(8.5),
        height: getPortraitSHeight(14.5),
      );
    }
  }

  Widget getBadgeText(String name) {
    return Text(
      name,
      style: TextStyle(color: text_black, fontSize: setSp(15)),
    );
  }

  void _getMyInfo() {
    UserApi().userInfo().then((res) {
      if (res.code == 200) {
        setState(() {
          this.userInfo = res.data;
        });
      }
    });
  }

  //弹出底部菜单
  void _showBottomMenu(BuildContext context) {
    showModalBottomSheet(
        context: context,
        //isScrollControlled: true,//设为true，此时为全屏展示

        builder: (BuildContext context) {
          return Container(
            color: Colors.white,
            height: 180,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                ListTile(
                  title: Text('拍照',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: text_black)),
                  onTap: () {
                    _takePhoto();
                    Navigator.pop(context);
                  },
                ),
                Divider(
                  height: 1,
                ),
                ListTile(
                  title: Text('相册',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: text_black)),
                  onTap: () {
                    _openPhotoAlbum();
                    Navigator.pop(context);
                  },
                ),
                Container(
                  color: bg_divider,
                  height: 10,
                ),
                ListTile(
                  title: Text('取消',
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 16, color: text_black)),
                  onTap: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            ),
          );
        });
  }

  PickedFile _image;
  final ImagePicker _picker = ImagePicker();

  ///拍照
  Future _takePhoto() async {
    PickedFile image = await _picker.getImage(
        source: ImageSource.camera, maxHeight: 400, maxWidth: 400);
    if (image != null) {
      LogUtil.d("_takePhoto obj  ${image.path}");
      _cropImage(image);
    }
  }

  ///打开相册
  Future _openPhotoAlbum() async {
    PickedFile image = await _picker.getImage(
        source: ImageSource.gallery, maxHeight: 400, maxWidth: 400);
    if (image != null) {
      LogUtil.d("_openPhotoAlbum obj  ${image.path}");
      _cropImage(image);
    }
  }

//剪裁
  _cropImage(PickedFile imageFile) async {
    setState(() {
      _image = imageFile;
    });
  }
}
